package com.lhf.springcloud.controller;

import com.lhf.springcloud.Entity.MajorInfo;
import com.lhf.springcloud.service.MajorServiceImpl;
import com.lhf.springcloud.utils.ExcelUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class MajorController {
    @Autowired
    private MajorServiceImpl majorService;
    @GetMapping("/majorData")
    @ApiOperation("专业相关数据")
    public String listUploadedFiles() throws IOException {
        return "majorData";
    }
    @RequestMapping(value = "/findAllMajorData",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("查询专业")
    public Map findAllData(){
        List<MajorInfo> allMajorData = majorService.findAllMajorData();
        Map map=new HashMap<>();
        map.put("code",0);
        map.put("msg","成功");
        map.put("count",allMajorData.size());
        map.put("data",allMajorData);
        return map;
    }
    /*根据专业代码查询专业信息*/
    @RequestMapping(value = "/findByMajorNumberData",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("通过专业代号查询专业")
    public Map findByMajorNumberData(String majorNumber){
        MajorInfo byMajorNumberData = majorService.findByMajorNumberData(majorNumber);
        Map map=new HashMap<>();
        map.put("code",0);
        map.put("msg","成功");
        map.put("data",byMajorNumberData);
        return map;
    }
    //@ApiOperation(value = "添加用户")
    @GetMapping("/majorDownFiles")
    @ResponseBody
    public void downloadLocal(HttpServletResponse response) throws FileNotFoundException {
        // 下载本地文件
        String fileName = "专业信息表.xlsx".toString(); // 文件的默认保存名
        // 读到流中
        String c = System.getProperty("user.dir");
        InputStream inStream = new FileInputStream(c+"/excel/专业信息模板.xlsx");// 文件的存放路径
//        InputStream inStream = new FileInputStream("E:\\测试练习code2\\诊改\\ZG\\file-upload\\src\\main\\resources\\templates\\excel\\专业信息模板.xlsx");// 文件的存放路径
        // 设置输出的格式
        response.reset();
        response.setContentType("bin");
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 循环取出流中的数据
        byte[] b = new byte[100];
        int len;
        try {
            while ((len = inStream.read(b)) > 0)
                response.getOutputStream().write(b, 0, len);
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //文件上传
    @PostMapping("/majorDownLoad")
    @ApiOperation("文件上传")
    @ApiImplicitParam(name="file",value = "需要上传的文件")
    public String handleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes){
        if(file.isEmpty()) {
            return "redirect:/majorData";
        }
        List<MajorInfo> list1= new ArrayList<>();
        try {
            InputStream inputStream = file.getInputStream();
            List<List<Object>> list = ExcelUtils.getCourseListByExcel(inputStream, file.getOriginalFilename());
            inputStream.close();

            for (int i = 1; i < list.size(); i++) {
                List<Object> courseList = list.get(i);

                MajorInfo course = new MajorInfo();
                if (courseList.size()==0){
                    break;
                }
                course.setMajorName(courseList.get(0).toString());
                course.setMajorNumber(courseList.get(1).toString());
                course.setMajorSchooling(courseList.get(2).toString());
                course.setMajorStartTime(courseList.get(3).toString());
                course.setMajorStatus(courseList.get(4).toString());
                course.setMajorBasics(courseList.get(5).toString());
                course.setMajorTarget(courseList.get(6).toString());
//                if (Double.valueOf(String.valueOf(courseList.get(5)))>100||Double.valueOf(String.valueOf(courseList.get(5)))<0){
//                    redirectAttributes.addFlashAttribute("message", "第"+i+"行学生成绩异常，请核对后上传!" );
//                    list1.clear();
//                    break;
//                }
                list1.add(course);
                // 执行插入操作

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (list1.size()>0){
            majorService.addCourse(list1);
        }
        //redirectAttributes.addFlashAttribute("message", "You successfully uploaded " + file.getOriginalFilename() + "!" );

        return "redirect:/majorData";  //重定向
    }
}
